package com.minxi.jsp.controller;

import com.minxi.jsp.javabean.User;
import com.minxi.jsp.servlet.WebBaseServlet;
import com.minxi.jsp.utils.DruidUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet(name = "JspServlet", urlPatterns = "/JspServlet")
public class JspServlet extends WebBaseServlet {
    /**
     * 用户登录
     */
    public void userLogin(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username").trim();
        String password = req.getParameter("password").trim();

        // 定义null值
        PreparedStatement st = null;
        Connection conn = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();
        try {

            conn = DruidUtil.DruidConnect();
            // 4.定义sql（预编译）
            String sql = "select * from user_info where user_name = ? and user_pwd = ?;";

            // 5.获取sql对象
            st = conn.prepareStatement(sql);
            st.setString(1, username);
            st.setString(2, password);

            // 6.执行sql语句
            rs = st.executeQuery();
            while (rs.next()) {
                // 把从数据库拿到的数据存起来
                Integer id = rs.getInt("id");
                String userName = rs.getString("user_name");
                String passWord = rs.getString("user_pwd");
                Integer age = rs.getInt("user_age");
                Integer sex = rs.getInt("user_sex");
                String userPhone = rs.getString("user_phone");
                String userAddress = rs.getString("user_address");
                Date userTime = rs.getDate("user_time");
                Integer roleType = rs.getInt("role_type");

                // 用拿到的数据创建用户对象
                User user = new User();
                user.setId(id);
                user.setUserName(userName);
                user.setPassWord(passWord);
                user.setAge(age);
                user.setSex(sex);
                user.setUserPhone(userPhone);
                user.setUserAddress(userAddress);
                user.setUserTime(userTime);
                user.setRoleType(roleType);

                // 往用户列表里添加用户对象
                users.add(user);
            }
            if (!users.isEmpty()) {
                resp.sendRedirect("jsp/2024-06-06/index2.jsp?id=" + users.get(0).getId());
            } else {
                resp.sendRedirect("jsp/2024-06-06/index1.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                DruidUtil.DruidClose(rs, st, conn);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 用户新增
     */
    public void userAdd(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.setCharacterEncoding("UTF-8");
        // 获取到前端的数据
        String userName = req.getParameter("userName").trim();
        String userPwd = req.getParameter("userPwd").trim();
        Integer userAge = Integer.valueOf(req.getParameter("userAge").trim());
        Integer userSex = Integer.valueOf(req.getParameter("userSex").trim());
        String userPhone = req.getParameter("userPhone").trim();
        String userAddress = req.getParameter("userAddress").trim();
        String time = req.getParameter("userTime").trim();
        java.sql.Date userTime;
        Integer roleType = Integer.valueOf(req.getParameter("roleType").trim());
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate = LocalDate.parse(time, formatter);
            userTime = java.sql.Date.valueOf(localDate);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 把拿到的数据实例化一个对象
        User user = new User();
        user.setUserName(userName);
        user.setPassWord(userPwd);
        user.setAge(userAge);
        user.setSex(userSex);
        user.setUserPhone(userPhone);
        user.setUserAddress(userAddress);
        user.setUserTime(userTime);
        user.setRoleType(roleType);

        PreparedStatement st = null;
        Connection conn = null;
        try {

            conn = DruidUtil.DruidConnect();
            // 4.定义sql（预编译）
            String sql = "insert into user_info(user_name,user_pwd,user_age,user_sex,user_phone,user_address,user_time,role_type)\n" +
                    "VALUES(?,?,?,?,?,?,?,?) ;";

            // 5.获取sql对象
            st = conn.prepareStatement(sql);
            st.setString(1, userName);
            st.setString(2, userPwd);
            st.setInt(3, userAge);
            st.setInt(4, userSex);
            st.setString(5, userPhone);
            st.setString(6, userAddress);
            st.setDate(7, userTime);
            st.setInt(8, roleType);

            // 6.执行sql语句
            int i = st.executeUpdate();
            if (i > 0) {
                resp.sendRedirect("jsp/2024-06-06/index2.jsp");
            } else {
                resp.sendRedirect("jsp/2024-06-06/new.jsp");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                DruidUtil.DruidClose(st, conn);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 用户修改
     */
    public void userUpdate(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.setCharacterEncoding("UTF-8");
        // 获取到前端的数据
        Integer Id = Integer.valueOf(req.getParameter("Id").trim());
        String userName = req.getParameter("userName").trim();
        String userPwd = req.getParameter("userPwd").trim();
        Integer userAge = Integer.valueOf(req.getParameter("userAge").trim());
        Integer userSex = Integer.valueOf(req.getParameter("userSex").trim());
        String userPhone = req.getParameter("userPhone").trim();
        String userAddress = req.getParameter("userAddress").trim();
        String time = req.getParameter("userTime").trim();
        java.sql.Date userTime;
        Integer roleType = Integer.valueOf(req.getParameter("roleType").trim());

        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate = LocalDate.parse(time, formatter);
            userTime = java.sql.Date.valueOf(localDate);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 把拿到的数据实例化一个对象
        User user = new User();
        user.setId(Id);
        user.setUserName(userName);
        user.setPassWord(userPwd);
        user.setAge(userAge);
        user.setSex(userSex);
        user.setUserPhone(userPhone);
        user.setUserAddress(userAddress);
        user.setUserTime(userTime);
        user.setRoleType(roleType);

        PreparedStatement st = null;
        Connection conn = null;
        try {

            conn = DruidUtil.DruidConnect();
            // 4.定义sql（预编译）
            String sql = "update user_info set " +
                    "user_name = ?," +
                    "user_pwd = ?," +
                    "user_age = ?," +
                    "user_sex = ?," +
                    "user_phone = ?," +
                    "user_address = ?," +
                    "user_time = ?," +
                    "role_type = ? where id = ?;";

            // 5.获取sql对象
            st = conn.prepareStatement(sql);
            st.setString(1, userName);
            st.setString(2, userPwd);
            st.setInt(3, userAge);
            st.setInt(4, userSex);
            st.setString(5, userPhone);
            st.setString(6, userAddress);
            st.setDate(7, userTime);
            st.setInt(8, roleType);
            st.setInt(9, Id);

            // 6.执行sql语句
            int i = st.executeUpdate();
            if (i > 0) {
                resp.sendRedirect("jsp/2024-06-06/index2.jsp");
            } else {
                resp.sendRedirect("jsp/2024-06-06/update.jsp?id=" + Id);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                DruidUtil.DruidClose(st, conn);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 用户删除
     */
    public void userDelete(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.setCharacterEncoding("UTF-8");
        // 获取到前端的数据
        Integer id = Integer.valueOf(req.getParameter("id").trim());

        PreparedStatement st = null;
        Connection conn = null;
        try {

            conn = DruidUtil.DruidConnect();
            // 4.定义sql（预编译）
            String sql = "delete from user_info where id = ?;";
            st = conn.prepareStatement(sql);
            // 5.获取sql对象
            st.setInt(1, id);

            // 6.执行sql语句
            int i = st.executeUpdate();
            if (i > 0) {
                resp.sendRedirect("jsp/2024-06-06/index2.jsp");
            } else {
                resp.sendRedirect("jsp/2024-06-06/delete.jsp?id=" + id);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                DruidUtil.DruidClose(st, conn);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}